package com.example.booksapplication.data;

import android.content.Context;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class BooksData {
    public static final String DATA_FILE_NAME = "data";
    private final Context context;
    List<BookStore> booksList;

    public BooksData(Context context) {
        this.context=context;
    }

    public List<BookStore> loadData() {
        booksList = new ArrayList<>();
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(context.openFileInput(DATA_FILE_NAME));
            booksList = (ArrayList<BookStore>) objectInputStream.readObject();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return booksList;
    }

    public void saveData() {
        ObjectOutputStream objectOutputStream=null;
        try{
            objectOutputStream=new ObjectOutputStream(context.openFileOutput(DATA_FILE_NAME, Context.MODE_PRIVATE));
            objectOutputStream.writeObject(booksList);
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(objectOutputStream!=null){
                    objectOutputStream.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }


    }
}
